package UI;

import javax.swing.*;
import java.awt.*;

public class MessageBubble extends JPanel {
    private boolean isOwnMessage;
    private String message;
    private String timestamp;

    public MessageBubble(String message, String timestamp, boolean isOwnMessage) {
        this.message = message;
        this.timestamp = timestamp;
        this.isOwnMessage = isOwnMessage;

        setOpaque(false);
        setLayout(new BorderLayout());
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int width = getWidth();
        int height = getHeight();

        if (isOwnMessage) {
            g2.setColor(new Color(220, 248, 198)); // 自己消息的背景色
        } else {
            g2.setColor(new Color(240, 240, 240)); // 他人消息的背景色
        }

        // 绘制圆角矩形气泡
        g2.fillRoundRect(0, 0, width, height, 15, 15);

        // 绘制三角形指向
        if (isOwnMessage) {
            int[] xPoints = {width - 10, width, width};
            int[] yPoints = {height - 10, height - 10, height};
            g2.fillPolygon(xPoints, yPoints, 3);
        } else {
            int[] xPoints = {10, 0, 0};
            int[] yPoints = {height - 10, height - 10, height};
            g2.fillPolygon(xPoints, yPoints, 3);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        // 根据消息内容计算合适的大小
        FontMetrics fm = getFontMetrics(getFont());
        int msgWidth = fm.stringWidth(message);
        int lineCount = (int) Math.ceil((double) msgWidth / 200);
        int height = lineCount * fm.getHeight() + 30; // 加上时间戳的高度

        return new Dimension(Math.min(msgWidth, 200) + 20, height);
    }
}